package com.vt.common.security.util;

import com.vt.admin.api.dto.user.redis.UserOrganization;
import com.vt.common.security.util.enums.DataScopeType;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Auther: panZha
 * @Date: 2018/11/20 11:23
 * @Description: 兼容一期的数据区隔工具类
 */
@Primary
@Component
public class SysClient extends DataScopeUtil{


    /**
     * 按人权限 （返回userId）
     *
     * @return
     */
    public List<String> getUserIds() {
        return new ArrayList(super.scope());
    }

    /**
     * 分公司权限 组织ID
     *
     * @return
     */
    public List<String> getCompanyIds() {
        return new ArrayList(chsByCompanyType(DataScopeType.COMPANY_BRANCH));
    }

    /**
     * 管理公司权限 组织ID
     *
     * @return
     */
    public List<String> getManagementCompanyIds() {
        return new ArrayList(chsByCompanyType(DataScopeType.COMPANY_MANAGER));
    }

    private Set<String> currUser() {
        Set<String> userSet = new HashSet();
        userSet.add(SecurityUtils.getUser().getId());
        return userSet;
    }


    private Set<String> chsByCompanyType(DataScopeType type) {
        List<UserOrganization> all = super.getOrgan();
        List<UserOrganization> currOs = super.byUser(all, currUser());

        Set<UserOrganization> roots = getRootNode(all, currOs, type);
        roots.addAll(currOs);

        Set<String> rs = super.getChildrenNode(roots, all);
        return rs;
    }


    private Set<UserOrganization> getRootNode(Collection<UserOrganization> all, Collection<UserOrganization> subList, DataScopeType scopeType) {
        Set<UserOrganization> roots = new HashSet();
        for (UserOrganization uo : subList) {
            super.searchRootNode(all, uo, scopeType, roots);
        }

        if (roots.size() == 0
                && scopeType == DataScopeType.COMPANY_BRANCH) {
            //没有上级分公司，用管理公司权限
            roots = getRootNode(all, subList, DataScopeType.COMPANY_MANAGER);
        }
        return roots;
    }

    public List<String> getChildrenCompany(String companyId) {
        return null;
    }

}
